
import sys
import os
import json
import argparse

# Force stdout to use UTF-8 encoding
sys.stdout.reconfigure(encoding='utf-8')

# Add the project root to the Python path to allow for absolute imports
project_root = os.path.dirname(os.path.abspath(__file__))
# Adjust project_root to point to ZY_agents directory
project_root = os.path.join(project_root, '..', '..')
project_root = os.path.abspath(project_root)

if project_root not in sys.path:
    sys.path.insert(0, project_root)
 

def _load_settings():
    settings_path = os.path.join(project_root, 'settings.txt')
    try:
        with open(settings_path, 'r', encoding='utf-8') as f:
            settings = json.load(f)
        return settings
    except FileNotFoundError:
        print(f"Error: settings.txt not found at {settings_path}")
        return {}
    except json.JSONDecodeError:
        print(f"Error: Could not decode JSON from settings.txt at {settings_path}")
        return {}

def web_fetch():
    """
    Command-line interface for performing a web fetch.
    """
    parser = argparse.ArgumentParser(description="Perform a web fetch using the built-in web_fetch tool.")
    parser.add_argument("prompt", type=str, help="The prompt containing URLs and instructions for web fetching.")
    args = parser.parse_args()

    if not args.prompt:
        print("Error: A prompt with URLs is required.")
        sys.exit(1)

    settings = _load_settings()
    userid = settings.get("userid")
    openid = settings.get("openid")

    if not userid or not openid:
        print("Error: userid or openid not found in settings.txt")
        sys.exit(1)

    print(f"Fetching web content for: '{args.prompt}'...")
    # Call the web_fetch function from default_api
    result = config.ZY_server_api_endpint.default_api.web_fetch(prompt=args.prompt)

    # Print the raw string result
    print(result)

if __name__ == "__main__":
    web_fetch()
